package com.bw.user_module.login;

import com.blankj.utilcode.util.LogUtils;
import com.bw.common.entity.SaveEntity;
import com.bw.common.mvvm.model.BaseRespository;
import com.bw.network_sdk.BaseEntity;
import com.bw.network_sdk.HttpType;
import com.bw.network_sdk.NetWorkFactory;
import com.bw.user_module.dao.UserDatabase;
import com.bw.user_module.user.UserEntity;

import java.util.Map;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

public class LoginRepository extends BaseRespository {

    Observable<BaseEntity>requestLogin(Map<String,Object>map){
        Observable<UserEntity>userEntityObservable =
                NetWorkFactory.factory(HttpType.TOKENSIGN)
                        .create(ApiService.class)
                        .requestLogin(createBody(map));
        return checkNetWork(userEntityObservable);
    }

    Observable<BaseEntity>saveUser(UserEntity entity, UserDatabase db){
        LogUtils.e("LoginRepository:saveUser");
        //手动创建被观察者任务,
        //依托于rxjava线程调度，
        //被观察者将在子线程中执行,
        //room增删改查将在子线程执行,
        //当rxjava的被观察者任务执行完成后,需要手动调用
        // 观察着的onnext以及onComplete
        Observable<SaveEntity>observable=
                new Observable<SaveEntity>() {
                    @Override
                    protected void subscribeActual(
                            Observer<? super SaveEntity> observer) {
                        db.userDao().delUser();
                        db.userDao().insertUser(entity.data);
                        SaveEntity saveEntity = new SaveEntity();
                        saveEntity.status = 200;
                        saveEntity.message ="保存成功";
                        observer.onNext(saveEntity);
                        observer.onComplete();
                    }
                };
        return functionObservable(observable);
    }

}
